<template>
  <div>
    <el-upload
      :class="{disable: fileList.length>0}"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="isShowpercent"
      :text-inside="true"
      :stroke-width="26"
      :percentage="percent"
      style="width:146px"
    />
    <el-dialog title="图片预览" :visible="isShowDialog" @close="closeDialog">
      <el-row type="flex" justify="center">
        <img :src="previewUrl" style="width:100%" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// 创建实例
const cos = new COS({
  SecretId: 'AKID61kDPL0PXP1NTJsABvNZU8UaPwCBtKVO',
  SecretKey: 'e29zYqse8MN8bokPnvwhBOKzOWNxGI3X'
})
export default {
  data() {
    return {
      isShowDialog: false,
      isShowpercent: false,
      percent: 0,
      previewUrl: '',
      fileList: []
    }
  },
  methods: {
    onPreview(file) {
      this.isShowDialog = true
      this.previewUrl = file.url
    },
    closeDialog() {
      this.isShowDialog = false
    },
    onRemove(file, newFileList) {
      setTimeout(() => {
        this.fileList = newFileList
        console.log(this.fileList, newFileList)
      }, 1100)
    },
    upload(params) {
      this.isShowpercent = true
      cos.putObject({
        // 储存桶名
        Bucket: 'hr69-1308572139',
        // 区域标志
        Region: 'ap-guangzhou',
        // 文件名
        Key: params.file.name,
        // 固定写法, 标准储存的意思
        StorageClass: 'STANDARD',
        // 文件对象本身
        Body: params.file,
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = Math.round(progressData.percent) * 100
        }
      }, (err, data) => {
        console.log(err || data)
        this.fileList[0].url = 'http://' + data.Location
        this.fileList[0].status = 'success'
        setTimeout(() => {
          this.isShowpercent = false
        }, 1000)
      })
    },
    onChange(file, newFileList) {
      this.fileList = newFileList
    },
    beforeUpload(file) {
      const maxSize = 2 * 1024 * 1024
      console.log(file.size)
      if (file.size > maxSize) {
        this.$message.warning('图片不能大于2M')
        return false
      }
      // 校验格式
      console.log(file.type)
      const typeList = ['image/jpeg', 'image/png', 'image/jpg']
      if (!typeList.includes(file.type)) {
        this.$message.warning('文件格式不是图片,请重新选择文件')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.disable{
    ::v-deep .el-upload--picture-card{
    display: none;
}
}
</style>

<style >

</style>
